<template>
	<view class="container">
		<view class="login-form">
			<view class="title">登录后，内容更有趣！</view>
			<input type="text" placeholder="用户名" v-model="username" class="input-field" />
			<input type="password" placeholder="密码" v-model="password" class="input-field" />
			<button @click="login" class="submit-button">登录</button>
			<view class="link-to-register">
				<text>没有账号？</text>
				<button @click="navigateToRegister" class="link-button">去注册</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				username: '',
				password: ''
			};
		},
		methods: {
			async login() {
				try {
					const result = await uniCloud.callFunction({
						name: 'getUser', // 确保这是正确的云函数名称
						data: {
							username: this.username,
							password: this.password
						}
					});

					// 检查云函数返回的数据
					if (result.result && result.result.success) {
						console.log("登录成功");
						// 保存数据到本地存储
						uni.setStorageSync('username', this.username);

						uni.showToast({
							title: "登录成功",
							duration: 1000
						});
						uni.navigateBack({
							delta: 2
						})

					} else {
						// 确保即使message未定义也能正确显示
						const errorMessage = result.result.message || "登录失败";
						console.log(errorMessage);
						uni.showToast({
							title: errorMessage,
							duration: 2000,
							image: "/static/cw.png"
						});
					}
				} catch (error) {
					console.log("处理错误", error);
					uni.show({
						title: "登录出错",
						duration: 1200,

					});
				}
			},
			navigateToRegister() {
				uni.navigateTo({
					url: "/pages/news_my/register/register"
				})
			},
			// onLoad(options) {
			// 	if (options.data) {
			// 		this.username = options.data;
			// 		console.log(this.username, "账号");
			// 	} else {
			// 		console.log("传输失败");
			// 	}
			// }
		}
	}
</script>

<style>
	.title {
		color: #000;
		text-align: center;
		line-height: 100rpx;
		font-size: 40rpx;
	}

	.container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
	}

	.login-form {
		width: 600rpx;
		padding: 40rpx;
		border-radius: 10rpx;
		padding-bottom: 500rpx;
	}

	.input-field {
		width: 100%;
		padding: 20rpx;
		margin-bottom: 30rpx;
		border: 2rpx solid #ddd;
		border-radius: 8rpx;
	}

	.submit-button {
		width: 100%;
		padding: 20rpx;
		background-color: #F5433F;
		color: white;
		border: none;
		border-radius: 8rpx;
		cursor: pointer;
	}

	.link-to-register {
		text-align: center;
		margin-top: 20rpx;
	}

	.link-button {
		background: #f1f1f1;
		border: none;
		color: #F5433F;
		cursor: pointer;
	}
</style>